package com.mspbots.rule.queue.tsheet;

import com.mspbots.cw.request.SheetsTimeDTO;
import com.mspbots.cw.request.SheetsUserDTO;
import com.mspbots.rule.exceptions.BaseRule;
import com.mspbots.rule.exceptions.tsheet.TSheetBaseRule;
import com.mspbots.rule.queue.BaseQueue;
import lombok.extern.slf4j.Slf4j;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

import static java.time.temporal.ChronoUnit.SECONDS;

/**
 * @ClassName com.mspbots.rule.queue.tsheet.TsheetBaseQueue
 * @Description TODO
 * @Author Jun
 * @Date 2019/9/2 16:12
 * @Version 1.0
 **/
@Slf4j
@Component
public class TsheetBaseQueue extends BaseQueue {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Async
    protected void onRule(String ruleName, SheetsTimeDTO sheetsTimeDTO) {
        try {
            if (checkRule(ruleName, sheetsTimeDTO.getTenantId())) {
                Map<String, Object> params = new HashMap<>();
                params.put("tenantId", sheetsTimeDTO.getTenantId());
                params.put("sheetUserId", sheetsTimeDTO.getSheetUserId());
                SheetsUserDTO sheetsUserDTO = coreClient.get("/sheet-users/info", params, SheetsUserDTO.class).block(Duration.of(5, SECONDS));
                if (sheetsUserDTO != null) {
                    sheetsTimeDTO.setTsUid(sheetsUserDTO.getId());
                    log.info("tsheet info {}", sheetsTimeDTO);
                    Rules rules = new Rules();
                    Class clazz = Class.forName(tenantRuleDTO.getClassName());
                    TSheetBaseRule instance = (TSheetBaseRule) clazz.getDeclaredConstructor().newInstance();
                    instance.init(tenantRuleDTO, messageProducer, messagesService, tenantUserMappingService,
                            tenantConfigurationService, coreClient, objectMapper);
                    instance.setStringRedisTemplate(stringRedisTemplate);
                    rules.register(instance);
                    Facts facts = new Facts();
                    facts.put(BaseRule.FACT, sheetsTimeDTO);
                    rulesEngine.fire(rules, facts);
                }
            }
        } catch (Exception e) {
            log.error("trigger [{}] fire error : {}", ruleName, e.getMessage());
            e.printStackTrace();
        }

    }
}
